﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace WMIUtil
{
   public static class WMIUtilStatic
    {
        private static ManagementObjectSearcher ExecQuery(ServerInfo serverInfo, string Query)
        {
            try
            {
                ConnectionOptions connection;
                if (string.IsNullOrEmpty(serverInfo.userName))
                { connection = new ConnectionOptions(); }
                else
                {
                    connection = new ConnectionOptions();
                    connection.Username = serverInfo.userName;
                    connection.Password = serverInfo.passWord;
                    //connection.Authority = "ntlmdomain:DOMAIN";
                }
                ManagementScope scope = new ManagementScope(
                    string.Format("\\\\{0}\\root\\CIMV2", serverInfo.serverName), connection);
                scope.Connect();


                ObjectQuery query = new ObjectQuery(Query);

                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(scope, query);

                return searcher;
            }

            catch (Exception ex)
            {
                Logger.LogError(ex, " ~ExecQuery " + serverInfo.serverName); 
                return null;
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////

        public static List<ServerDisks> GetDiskSpace(ServerInfo serverInfo)
        {
            List<ServerDisks> disks = new List<ServerDisks>();
            try
            {
                string query = "SELECT Name,Status,Size,FreeSpace FROM Win32_LogicalDisk";

                ManagementObjectSearcher searcher = ExecQuery(serverInfo, query);

                ServerDisks disk;
                if (searcher == null) { return null; }
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    disk = new ServerDisks();
                    disk.DiskName = (queryObj["Name"] != null ? queryObj["Name"].ToString() : "");
                    disk.Status = (queryObj["Status"] != null ? queryObj["Status"].ToString() : "");
                    disk.TotalSpace = Int64.Parse((queryObj["Size"] != null ? queryObj["Size"].ToString() : "0"));
                    disk.FreeSpace = Int64.Parse((queryObj["Size"] != null ? queryObj["FreeSpace"].ToString() : "0"));

                    disks.Add(disk);
                }
            }
            catch (Exception ex)
            {              
                Logger.LogError(ex, "~GetDiskSpace " + serverInfo.serverName);
                return null;
            }
            return disks;
        }



        public static List<ServerServices> GetServices(ServerInfo serverInfo)
        {
            List<ServerServices> services = new List<ServerServices>();
            try
            {
                string query = string.Format("SELECT DisplayName,State,StartMode FROM Win32_Service WHERE DisplayName like '%{0}%' or DisplayName like '%{1}%' ", "SQL", "SHAREPOINT");

                ManagementObjectSearcher searcher = ExecQuery(serverInfo, query);

                ServerServices service;
                if (searcher == null) { return null; }
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    service = new ServerServices();
                    service.ServiceName = (queryObj["DisplayName"] != null ? queryObj["DisplayName"].ToString() : "");
                    service.Status = (queryObj["State"] != null ? queryObj["State"].ToString() : "");
                    service.StartMode = (queryObj["StartMode"] != null ? queryObj["StartMode"].ToString() : "");
                    services.Add(service);
                }
            }
            catch (ManagementException e)
            {
                //
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "~GetServices " + serverInfo.serverName);
                return null;
            }
            return services;
        }


        
        public static List<ServerMemory> GetServerMemory(ServerInfo serverInfo)
        {
            List<ServerMemory> info = new List<ServerMemory>();
            try
            {
                string query = "SELECT FreePhysicalMemory,TotalVisibleMemorySize FROM Win32_OperatingSystem";

                ManagementObjectSearcher searcher = ExecQuery(serverInfo, query);

                ServerMemory service;
                if (searcher == null) { return null; }
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    service = new ServerMemory();
                    service.FreePhysicalMemory = (queryObj["FreePhysicalMemory"] != null ? Int64.Parse(queryObj["FreePhysicalMemory"].ToString()) : 0);
                    service.TotalVisibleMemorySize = (queryObj["TotalVisibleMemorySize"] != null ? Int64.Parse(queryObj["TotalVisibleMemorySize"].ToString()) : 0);

                    //if (service.ServiceName.Contains("Ventyx") || service.ServiceName.Contains("SQL"))
                    {
                        info.Add(service);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "~GetServerMemory " + serverInfo.serverName);
                return null;
            }
            return info;
        }

        public static List<ServerCPU> GetServerCPU(ServerInfo serverInfo)
        {
            List<ServerCPU> info = new List<ServerCPU>();
            try
            {
                string query = "SELECT LoadPercentage FROM Win32_OperatingSystem";

                ManagementObjectSearcher searcher = ExecQuery(serverInfo, query);

                ServerCPU service;
                if (searcher == null) { return null; }
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    service = new ServerCPU();
                    service.CPULoadPercentage = (queryObj["LoadPercentage"] != null ? Int64.Parse(queryObj["LoadPercentage"].ToString()) : 0);
                    info.Add(service);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "~GetServerCPU " + serverInfo.serverName);
                return null;
            }
            return info;
        }


        public static List<MessageQueue> GetMessageQueues(ServerInfo serverInfo)
        {
            List<MessageQueue> info = new List<MessageQueue>();
            try
            {
                string query = "Select Name,MessagesInQueue From Win32_PerfRawData_MSMQ_MSMQQueue where MessagesInQueue > 0";

                ManagementObjectSearcher searcher = ExecQuery(serverInfo, query);

                MessageQueue service;
                if (searcher == null) { return null; }
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    service = new MessageQueue();
                    service.QueueName = (queryObj["Name"] != null ? queryObj["Name"].ToString() : "");
                    service.NumberOfMessages = (queryObj["MessagesInQueue"] != null ? int.Parse(queryObj["MessagesInQueue"].ToString()) : 0);

                    info.Add(service);

                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "~GetMessageQueues " + serverInfo.serverName);
                return null;
            }
            return info;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////


    }
}
